<?php

namespace App\Service\Admin;

use App\Model\Admin;
use App\Model\AdminLoginLog;
use App\Service\BaseService;
use App\Utils\StrHash;
use Hyperf\Contract\SessionInterface;
use Hyperf\Di\Annotation\Inject;

/**
 * 登录服务
 * @package App\Service\Admin
 */
class LoginService extends BaseService
{
    /**
     * @Inject()
     * @var SessionInterface
     */
    private $session;

    /**
     * 登录验证
     * @param array $request
     * @param string $ip 请求IP
     * @return array
     */
    public function loginVerify(array $request, string $ip)
    {
        // 查询用户
        $admin = Admin::query()->where("username", $request["username"])->first();
        if (!$admin) {
            return $this->baseResponse(1, "用户不存在");
        }
        // 密码校验
        $flag = StrHash::very($request['password'], $admin['password']);
        if (!$flag) {
            $this->loginLog($admin->id, $request["username"], $request["password"], 1, 2);
            return $this->baseResponse(1, "密码不正确");
        }
        // 设置登陆成功后钩子
        $admin['login_num'] += 1;
        $admin["last_login_time"] = time();
        $admin["last_login_ip"] = $ip;
        $admin->save();
        $this->loginLog($admin->id, $request["username"], $request["password"], 1, 1);
        // 设置Session
        $this->session->set("admin", $admin);
        return $this->baseResponse(0, "登录成功", $this->session->get("admin"));
    }

    /**
     * 记录登录后日志
     * @param $adminId
     * @param $username
     * @param $password
     * @param $type
     * @param $status
     */
    public function loginLog($adminId, $username, $password, $type, $status)
    {
        AdminLoginLog::query()->create([
            'admin_id' => $adminId,
            'username' => $username,
            'password' => $password,
            'type'     => $type,
            'status'   => $status,
        ]);
    }
}